import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ExtendHttpService} from "../../../../common/extend-http.service";
import {debounceTime} from "rxjs/operator/debounceTime";
import {Observable} from 'rxjs/Rx';
import {TipService} from "../../../services/tip.service";
import {EssService} from "../../ess.service";

@Component({
  selector: 'app-material-add',
  templateUrl: './material-add.component.html',
  styleUrls: ['./material-add.component.css']
})
export class MaterialAddComponent implements OnInit {

  tipType = 'error';

  editInfo: any = {
    'mt.unit': [],
    'mt.sort': '999',
  };

  id: any = '';

  tips1 = '请输入物料名称';
  tips2 = '';
  tips3 = '';

  foodList: any = []; // 绑定的菜列表
  showList: any = false; // 下拉搜索菜单是否出现
  foodName: any = '选择'; // 选择的绑定物品名字

  constructor(
    private ext: ExtendHttpService,
    public ess: EssService,
    private router: Router,
    private route: ActivatedRoute,
    private tips: TipService
  ) {
  }

  ngOnInit() {
    this.getCardClass();

    // 取到会员卡id
    this.id = this.route.queryParams['value']['id'];
    if (this.id) {
      this.getEditInfo(this.id);
    }
  }

  // 添加单位
  addUnit() {
    this.editInfo['mt.unit'].push({
      index: this.editInfo['mt.unit'].length + 1,
      mark: this.editInfo['mt.unit'].length + 1 + 'mark',
      conversion: '',
      unit: ''
    });
  }

  // 删除单位
  deleteUnit(h) {
    this.editInfo['mt.unit'].splice(h, 1);
  }

  // 获取添加物料时选择绑定的菜
  getCardClass() {
    this.ext.get('/merchantApp/inventory/materiel/getfoodList', {}).subscribe(res => {
      let info = res.json();
      if (info.code === '0') {
        this.foodList = info.list;
      } else {
        this.ess.errTips(info);
      }
    });
  }

  // 是否显示下拉框
  isShowList(e) {
    e.stopPropagation();
    this.showList = !this.showList;
  }

  // 下拉框搜索
  searchKey(e, el) {
    let input = Observable.fromEvent(el, 'input');
    input.debounceTime(500)
      .subscribe(ev => {
        // console.log(el.value);
        this.foodList.forEach(item => {
          if (item.name.indexOf(el.value) === -1) {
            item.show = true;
          } else {
            item.show = false;
          }
        });
      });
  }

  // 点击选择下拉框
  chooseRes(v) {
    this.foodName = v.name;
    this.editInfo['mt.food_id'] = v.id;
    this.showList = false;
  }

  // clear清除选择
  clearChoose() {
    this.foodName = '选择';
    this.editInfo['mt.food_id'] = '';
    this.showList = false;
  }

  // 获取编辑信息
  getEditInfo(id) {
    this.ext.get('/merchantApp/inventory/materiel/findById', {id: id}).subscribe(res => {
      let info = res.json();
      if (info.code === '0') {
        // console.log(info, '编辑信息');
        let obj = info['materiel'];
        for (let i in obj) {
          this.editInfo['mt.' + i] = obj[i] || '';
        }
        this.editInfo['mt.unit'] = JSON.parse(this.editInfo['mt.unit']);
        setTimeout(() => {
          this.foodList.forEach(item => {
            if (item.id === this.editInfo['mt.food_id']) {
              this.chooseRes(item);
            }
          });
        }, 300);
      } else {
        this.ess.errTips(info);
      }
    });
  }

  // 验证方法
  validationMethods() {
    if (!this.editInfo['mt.name'] || this.editInfo['mt.name'].length > 20) {
      this.tips1 = '请填写物料名称（1-20字）！';
      this.tips.change(true, this.tips1);
    } else {
      this.tips1 = '';
    }
    if (!this.editInfo['mt.unit'].length) {
      this.tips2 = '请编辑物料单位！';
      this.tips.change(true, this.tips2);
    } else {
      this.tips2 = '';
    }

    if (!this.tips1 && !this.tips2) {
      return true;
    } else {
      return false;
    }
  }

  // 保存
  save() {
    if (!this.validationMethods()) {
      return;
    }

    let param = Object.assign({}, this.editInfo);
    param['mt.unit'] = JSON.stringify(param['mt.unit']);
    let url = this.id ? '/merchantApp/inventory/materiel/update' : '/merchantApp/inventory/materiel/add';
    this.ext.post(url, param).subscribe(res => {
      this.handInfo(res.json());
    });
  }

  // 请求返回信息处理
  handInfo(info) {
    if (info.code === '0') {
      this.tipType = 'success';
      this.tips.change(true, info.message);
      setTimeout(() => {
        this.back();
      }, 500);
    } else {
      this.tips.change(true, this.ess.errTips(info));
    }
  }

  // 取消添加
  back() {
    this.router.navigateByUrl('/main/ess/material');
  }

}
